<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="主订单编号:" prop="orderCode">
          <el-input v-model="queryParams.orderCode" clearable placeholder="请输入主订单编号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="子订单编号:" prop="orderCarCode">
          <el-input v-model="queryParams.orderCarCode" clearable placeholder="请输入子订单编号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车型:" prop="carModelId">
          <linkage-select v-model="carModelId" :check-strictly="false" @changeNode="linkageChange" placeholder="请选择车型" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车辆状态:" prop="orderCarStatus">
          <el-select v-model="queryParams.orderCarStatus" clearable>
            <template v-for="dict in dict.type.order_car_status">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="颜色:" prop="appearanceColor">
          <el-input v-model="queryParams.appearanceColor" clearable placeholder="请输入颜色"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车牌号:" prop="carPlateNo">
          <el-input v-model="queryParams.carPlateNo" clearable placeholder="请输入车牌号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车架号:" prop="carVinNo">
          <el-input v-model="queryParams.carVinNo" clearable placeholder="请输入车架号"></el-input>
        </el-form-item>
      </el-col>
    </SearchContent>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" @click="newReplacement" :disabled="!radio"> 新增替车 </el-button>
      </div>
      <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
        <!-- 操作插槽 -->
        <template slot="tableColAc">
          <el-table-column label="" align="center" width="35" fixed>
            <template scope="scope">
              <el-radio
                :disabled="!((scope.row.orderStatus == 3 || scope.row.orderStatus == 4 || scope.row.orderStatus == 5 || scope.row.orderStatus == 6 || scope.row.orderStatus == 7 || scope.row.orderStatus == 8) && scope.row.addOrNot == 0)"
                :label="scope.row.orderCarId"
                v-model="radio"
                @change="changeRadio"
              >
                {{ scope.row.aaa ? scope.row.aaa : '' }}
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="350" fixed align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                type="text"
                v-if="scope.row.orderStatus !== 1 && scope.row.orderStatus !== 2 && scope.row.orderStatus !== 9 && scope.row.orderStatus !== 10 && (scope.row.substituteControlBtn == 1 || scope.row.substituteMaintenanceBtn == 1)"
                v-hasPermi="['suborderManagement:suborderView:vehicle']"
                @click="replaceCar(1, scope.row)"
              >
                替车
              </el-button>
              <el-button
                type="text"
                v-if="scope.row.orderStatus !== 1 && scope.row.orderStatus !== 2 && scope.row.orderStatus !== 9 && scope.row.orderStatus !== 10 && scope.row.isChangeTheSubstitutionCar == 1"
                v-hasPermi="['suborderManagement:suborderView:vehicleChange']"
                @click="replaceCar(2, scope.row)"
              >
                替车变更
              </el-button>
              <el-button
                type="text"
                v-hasPermi="['suborderManagement:suborderView:vehicleDetail']"
                v-if="scope.row.orderStatus !== 1 && scope.row.orderStatus !== 2 && scope.row.orderStatus !== 9 && scope.row.orderStatus !== 10 && scope.row.isSubstituteCarRecords == 1"
                @click="replaceCarDetail(scope.row)"
              >
                替车记录
              </el-button>
              <el-button type="text" v-hasPermi="['suborderManagement:suborderView:detail']" @click="detail(scope.row)"> 详情 </el-button>
              <el-button v-hasPermi="['suborderManagement:suborderView:assignedDriverAgin']" v-if="scope.row.driverId > 0" type="text" @click="assignedDriver(2, scope.row)"> 重新分配司机 </el-button>
              <el-button v-hasPermi="['suborderManagement:suborderView:assignedDriver']" type="text" @click="assignedDriver(1, scope.row)" v-else> 分配司机 </el-button>
              <el-button v-if="scope.row.orderCarStatusStr == '用车中'" type="text" v-hasPermi="['suborderManagement:suborderView:returnTheCar']" @click="returnTheCar(scope.row)"> 还车 </el-button>
              <!-- <template v-if="scope.row.orderCarRenewalBtn==1">
								<el-button 
									v-if="scope.row.orderCarOriginalRenewalBtn==1"
									type="text" 
									@click="OriginalVehicle"
									v-hasPermi="['suborderManagement:suborderView:raw']"> 
									原车续签 
								</el-button> 
								<el-button 
									v-if="scope.row.orderCarChangeRenewalBtn==1"
									type="text" 
									@click=" _toPage({ name: 'MainChangeSign', })" 
									v-hasPermi="[ 'suborderManagement:suborderView:change',]"> 
									换车续签 
								</el-button> 
							</template> -->
              <el-button
                type="text"
                v-if="scope.row.orderCarChangeBtn == '1'"
                @click="
                  _toPage({
                    path: '/vehicleOrder/suborderManagement/contractChange',
                    name: 'MinContractChange',
                    query: {
                      orderCarId: scope.row.orderCarId,
                    },
                  })
                "
                v-hasPermi="['suborderManagement:suborderView:contract']"
              >
                合同变更
              </el-button>
            </template>
          </el-table-column>
        </template>
        <!-- 普通列插槽 -->
        <template slot="tableCol">
          <el-table-column label="主订单编号" align="center" prop="orderCode" min-width="200px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span @click="orderDetail(scope.row)" style="color: #1890ff; cursor: pointer">
                {{ scope.row.orderCode }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="子订单编号" align="center" prop="orderCarCode" min-width="200px" show-overflow-tooltip />
          <el-table-column label="车辆状态" align="center" prop="orderCarStatusStr" />
          <el-table-column label="出租方" align="center" prop="lessorName" min-width="150px" show-overflow-tooltip />
          <el-table-column label="承租方" align="center" prop="leaseeName" min-width="230px" show-overflow-tooltip />
          <el-table-column label="品牌" align="center" prop="carBrandName">
            <!-- <template slot-scope="scope">
              <span style="color: #1890ff;">{{ scope.row.carBrandName }}</span>
            </template> -->
          </el-table-column>
          <el-table-column label="车系" align="center" prop="carSeriesName" min-width="150px" show-overflow-tooltip>
            <!-- <template slot-scope="scope">
              <span style="color: #1890ff;">{{ scope.row.carSeriesName }}</span>
            </template> -->
          </el-table-column>
          <el-table-column label="车型" align="center" prop="carModelName" min-width="250px" show-overflow-tooltip>
            <!-- <template slot-scope="scope">
              <span style="color: #1890ff;">{{ scope.row.carModelName }}</span>
            </template> -->
          </el-table-column>
          <el-table-column label="能源类型" align="center" prop="carPowerTypeStr" />
          <el-table-column label="颜色" align="center" prop="appearanceColor" />
          <el-table-column label="每期租金(元)" align="center" prop="planRent" width="120">
            <template slot-scope="scope">
              <span>
                {{ format_thousand(scope.row.planRent) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="租期(月)" align="center" prop="planTenancyTypeStr" />
          <el-table-column label="加装费(元)" align="center" prop="attachedDecorationAmount" width="90">
            <template slot-scope="scope">
              <span>
                {{ format_thousand(scope.row.attachedDecorationAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="使用性质" align="center" prop="operationTypeStr" />
          <el-table-column label="车牌号" align="center" prop="carPlateNo" min-width="100px" show-overflow-tooltip />
          <el-table-column label="车架号" align="center" prop="carVinNo" min-width="180px" show-overflow-tooltip />
          <el-table-column label="交车时间" align="center" prop="deliveryTime" min-width="180px" show-overflow-tooltip />
          <el-table-column label="交车工作人员" align="center" prop="deliveryUserName" width="100" />
        </template>
      </table-page>
    </div>
    <!-- 添加或修改测试单表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body class="form-dialog" width="35%">
      <div style="width: 70%; margin: 0 auto">
        <el-form ref="formDig" :model="formDig" label-width="100px" :rules="rulesDig">
          <el-form-item label="出租方:">
            <span>{{ formDig.lessorName }}</span>
          </el-form-item>
          <el-form-item label="承租方:">
            <span>{{ formDig.leaseeName }}</span>
          </el-form-item>
          <el-form-item label="品牌:">
            <span>{{ formDig.carBrandName }}</span>
          </el-form-item>
          <el-form-item label="车型:">
            <span>{{ formDig.carModelName }}</span>
          </el-form-item>
          <el-form-item label="车系:">
            <span>{{ formDig.carSeriesName }}</span>
          </el-form-item>
          <el-form-item label="车牌号:">
            <span>{{ formDig.carPlateNo }}</span>
          </el-form-item>
          <el-form-item label="分配司机:" prop="driverId">
            <el-select v-model="formDig.driverId" filterable clearable style="width: 90%">
              <template v-for="item in driverList">
                <el-option :label="item.driverName" :value="item.driverId" :key="item.driverId"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SearchContent from '@/components/SearchContent/index.vue'
import { getOrderCar, getDriverListName, assignDriver, isApprovalProcess } from '@/api/vehicleOrder'
import LinkageSelect from '@/views/components/linkageSelect'
export default {
  name: 'SuborderView',
  components: {
    SearchContent,
    LinkageSelect,
  },
  dicts: ['order_car_status'],
  data() {
    return {
      driverList: [],
      title: '分配司机',
      open: false,
      carModelId: [],
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: '',
      },
      radio: '',
      total: 0,
      dataList: [],
      orderCarId: '',
      // 表单参数
      form: {},
      formDig: {},
      rulesDig: {
        driverId: [
          {
            required: true,
            message: '请选择司机',
            trigger: 'change',
          },
        ],
      },
      orderCarCode: '',
      carType: '',
      orderId: '',
      calcSchemeId: '',
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 单选切换
    changeRadio() {
      // this.$refs['el-table']?.table_clearSelection()
      this.orderCarCode = this.dataList.filter((v) => v.orderCarId === this.radio)[0]?.orderCarCode
      this.carType = this.dataList.filter((v) => v.orderCarId === this.radio)[0]?.carType
      this.orderId = this.dataList.filter((v) => v.orderCarId === this.radio)[0]?.orderId
      this.calcSchemeId = this.dataList.filter((v) => v.orderCarId === this.radio)[0]?.calcSchemeId
    },
    // 新增替车
    newReplacement() {
      this._toPage({
        name: 'CarReplacementService',
        query: {
          // 新增替车按钮  1是新增提车，2是维保替车，3是限行替车   4混合替车
          btnType: 1,
          orderId: this.radio,
          orderCarCode: this.orderCarCode,
          carType: this.carType,
          IdOrder: this.orderId,
          calcSchemeId: this.calcSchemeId,
        },
      })
    },
    async getDriverListName(orderId) {
      let params = {
        orderId,
      }
      try {
        let res = await getDriverListName(params)
        this.driverList = res.rows
      } catch (error) {}
    },
    cancel() {
      this.open = false
    },
    submitForm() {
      this.$refs['formDig'].validate((valid) => {
        if (valid) {
          this.open = false
          let data = {
            orderCarId: this.orderCarId,
            driverId: this.formDig.driverId,
          }
          assignDriver(data).then((res) => {
            this.$message.success(`${this.title}成功`)
            this.getList()
          })
        }
      })
    },
    assignedDriver(type, row) {
      this.$refs['formDig'] && this.$refs['formDig'].resetFields()
      console.log(type, row)
      this.open = true
      this.type = type
      this.getDriverListName(row.orderId)
      this.formDig = { ...row }
      this.orderCarId = row.orderCarId
      if (row.driverId == -1) {
        this.formDig.driverId = null
      }
      if (type == '1') {
        this.title = '分配司机'
      } else {
        this.title = '重新分配司机'
      }
    },
    linkageChange(val) {
      this.carModelId = val
    },
    // 订单详情
    orderDetail(row) {
      this._toPage({
        name: 'OrderDetails',
        query: {
          type: row.carType,
          orderId: row.orderId,
          calcSchemeId: row.calcSchemeId,
        },
      })
    },
    // 还车
    returnTheCar(row) {
      this._toPage({
        name: 'CommitReturnCar',
        query: {
          orderNo: row.orderCarCode,
        },
      })
    },
    // 替车
    replaceCar(type, row) {
      this.orderCarId = row.orderCarId
      let btnType = null
      // 新增替车按钮  1是新增提车，2是维保替车，3是限行替车, 4是混合替车
      if (row.substituteMaintenanceBtn == 1 && row.substituteControlBtn == 1) {
        btnType = 4
      } else if (row.substituteMaintenanceBtn == 1) {
        btnType = 2
      } else if (row.substituteControlBtn == 1) {
        btnType = 3
      }
      this.$confirm('是否选择额度申请中的替车服务', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      })
        .then(() => {
          console.log(this.orderCarId, 'orderCarId')
          let params = {
            orderId: this.orderCarId,
          }
          isApprovalProcess(params).then((res) => {
            // data为null  代表没有正在审批的替车流程 直接跳转页面
            if (res.code == 200 && res.data == null) {
              // this.$message.error('您有正在进行的替车服务')
              this._toPage({
                name: 'CarReplacementService',
                query: {
                  // 新增替车按钮  1是新增提车，2是维保替车，3是限行替车, 4是混合替车
                  btnType,
                  orderId: this.orderCarId,
                  orderCarCode: row.orderCarCode,
                  carType: row.carType,
                  IdOrder: row.orderId,
                  calcSchemeId: row.calcSchemeId,
                },
              })
            }
          })
        })
        .catch(() => {})
    },
    // 替车详情
    replaceCarDetail(row) {
      this._toPage({
        name: 'CarReplacementServiceDetail',
        query: {
          orderId: row.orderCarId,
          carType: row.carType,
          IdOrder: row.orderId,
          calcSchemeId: row.calcSchemeId,
        },
      })
    },
    // 详情
    detail(row) {
      this.$router.push({
        name: 'SuborderDetail',
        query: {
          id: row.orderCarId,
          orderCarCode: row.orderCarCode,
          // estimatedDeliveryTime: row.estimatedDeliveryTime,
          beFrom: 'SuborderView',
          orderId: this.$route.query.orderId,
        },
      })
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true
      this.queryParams.carModelId = this.carModelId[2]?.id
      this.queryParams.orderId = this.$route.query.orderId ? this.$route.query.orderId : ''
      getOrderCar(this.queryParams).then((res) => {
        if (res.code == '200') {
          const { rows, total } = res
          this.dataList = rows
          this.total = total
          this.loading = false
        }
      })
    },
    reset() {
      this.form = {}
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      ;(this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }),
        (this.carModelId = [])
      this.radio = ''
      this.handleQuery()
    },
  },
}
</script>

<style lang="scss" scoped>
.pagination-container {
  padding: 0 20px 50px !important;
}

.form-dialog {
  ::v-deep .el-dialog__header {
    padding: 10px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .box-card {
    margin-bottom: 20px;

    .card-title {
      font-size: 16px;
      position: relative;
      margin-left: 8px;
      padding: 0;
    }

    .card-title::after {
      content: '';
      width: 4px;
      height: 18px;
      background-color: aqua;
      display: block;
      position: absolute;
      left: -12px;
      top: 2px;
    }
  }
}
</style>
